from flask import (
    redirect,
    url_for,
    Blueprint,
    render_template,
    request
)
import threading
import sys
from utils.myitchat import mychat
from utils.decorators import is_login
import random
import os
import math
import re
import jieba
import jieba.analyse

import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image

import requests


bp = Blueprint('front', __name__, url_prefix='/front')

context = {}


@bp.route('/login/')
def login():
    root = sys.path[0]+'/static/'
    try:
        if os.path.isdir(root + 'imgs'):
            for s in os.listdir(root + 'imgs'):
                if s:
                    os.remove(root + 'imgs/' + s)
        if os.path.exists(root + 'all.png'):
            os.remove(root + 'all.png')
        if os.path.exists(root + 'meiriyitu.png'):
            os.remove(root + 'meiriyitu.png')
        if os.path.exists(root + 'wordclond.png'):
            os.remove(root + 'wordclond.png')

        context.clear()
    except OSError:
        print()
    else:
        print('缓存文件删除成功！')

    return render_template('login.html')


@bp.route('/', endpoint='index')
@is_login
def hello_world():
    print(mychat.myself.nick_name)
    return render_template('index.html', **context)


@bp.route('/allfriends/')
@is_login
def allfriends():
    del_friends = []
    all_friends = mychat.bot.friends(update=True)
    for friend in all_friends:
        print(friend.__dict__)
        print(friend)
        print(friend.nick_name)
        if friend.is_friend == False:
            del_friends.append(friend.nick_name)
    context['all_friends'] = (len(all_friends), del_friends, all_friends)
    return render_template('index.html', **context)


@bp.route('/allfriendsavatar/')
@is_login
def allfriendsavatar():
    all_friends = mychat.bot.friends()
    threads = []
    for friend in all_friends:
        th = threading.Thread(target=saveavatar, args=(friend,))
        th.start()
        threads.append(th)

    for th in threads:
        th.join()
    createImg()
    is_show_avatar = False
    if os.path.isfile(sys.path[0] + '/static/' + 'all.png'):
        is_show_avatar = True

    context['is_show_avatar'] = is_show_avatar
    return render_template('index.html', **context)


@bp.route('/friendslocal/')
@is_login
def friendslocal():
    # 使用一个字典统计各省好友数量
    province_dict = {'北京': 0, '上海': 0, '天津': 0, '重庆': 0,
                     '河北': 0, '山西': 0, '吉林': 0, '辽宁': 0, '黑龙江': 0,
                     '陕西': 0, '甘肃': 0, '青海': 0, '山东': 0, '福建': 0,
                     '浙江': 0, '台湾': 0, '河南': 0, '湖北': 0, '湖南': 0,
                     '江西': 0, '江苏': 0, '安徽': 0, '广东': 0, '海南': 0,
                     '四川': 0, '贵州': 0, '云南': 0,
                     '内蒙古': 0, '新疆': 0, '宁夏': 0, '广西': 0, '西藏': 0,
                     '香港': 0, '澳门': 0}

    # 统计省份
    all_friends = mychat.bot.friends()
    for friend in all_friends:
        if friend.province in province_dict.keys():
            province_dict[friend.province] += 1

    # 为了方便数据的呈现，生成JSON Array格式数据
    data = []
    for key, value in province_dict.items():
        data.append({'name': key, 'value': value})

    context['local_data'] = data
    return render_template('index.html', **context)


@bp.route('/friendssex/')
@is_login
def friendssex():
    sex_dict = {'male': 0, 'female': 0}
    all_friends = mychat.bot.friends(update=True)
    for friend in all_friends:
        # 统计性别
        if friend.sex == 1:
            sex_dict['male'] += 1
        elif friend.sex == 2:
            sex_dict['female'] += 1
    context['sex_dict'] = sex_dict
    return render_template('index.html', **context)


@bp.route('/friendssign/')
@is_login
def friendssign():
    signlist = []
    all_friends = mychat.bot.friends(update=True)
    for friend in all_friends:
        # 统计签名
        signature = friend.signature
        if signature:
            signature = signature.strip().replace('emoji', '').replace('span', '').replace('class', '')
            rep = re.compile('1f\d+\w*|[<>/=]')
            signature = rep.sub('', signature)
            signlist.append(signature)
    all_sign_text = ''.join(signlist)
    # 使用jb分词
    word_list = jieba.cut(all_sign_text)
    word_space_split = ' '.join(word_list)
    tags = jieba.analyse.extract_tags(word_space_split, topK=20)
    print(tags)
    coloring = np.array(Image.open(sys.path[0]+'/static/' + "beijing.jpg"))
    my_wordcloud = WordCloud(background_color="white", max_words=1000,
                             width=500, height=500, mask=coloring, max_font_size=100,min_font_size=13, random_state=42, scale=1,
                             font_path="simkai.ttf").generate(word_space_split)
    image_colors = ImageColorGenerator(coloring)
    plt.imshow(my_wordcloud.recolor(color_func=image_colors))
    plt.axis("off")
    plt.savefig(sys.path[0]+'/static/' + "wordclond.png")

    is_show_wordclond = False
    if os.path.isfile(sys.path[0]+'/static/'+'wordclond.png'):
        is_show_wordclond = True

    context['is_show_wordclond'] = is_show_wordclond
    return render_template('index.html', **context)


@bp.route('/getonemsg/')
@is_login
def getonemsg():
    send_msg = spiderOne()
    mychat.bot.file_helper.send_image(sys.path[0]+'/static/'+'meiriyitu.png')
    mychat.bot.file_helper.send_msg(msg=send_msg[1])
    return render_template('index.html')


# 爬取one每日一图
def spiderOne():
    url = 'http://wufazhuce.com/'
    request_header = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        'Host': 'wufazhuce.com',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Cookie': 'ANGSESSID=kc1f7kc628np844igprumrfa32; Hm_lvt_f5c3b24a04c561936d708b55833d8294=1533015042; Hm_lpvt_f5c3b24a04c561936d708b55833d8294=1533020069'
    }
    response = requests.get(url, headers=request_header).text
    data = re.findall(r'<img class="fp-one-imagen" src="(.*?)".*/>.*<div class="fp-one-cita">.*<a.*>(.*?)</a>.*<div class="clearfix"></div>', response, re.S)[0]
    img = requests.get(url=data[0]).content
    with open(sys.path[0]+'/static/'+'meiriyitu.png', 'wb') as f:
        f.write(img)
        f.close()
    return data


# 多线程保存用户头像到本地
def saveavatar(friend):
    print('新建线程：%s 开始任务' %threading.current_thread())
    avatar_path = sys.path[0] + '/static/imgs/' + friend.nick_name + '.jpg'

    with open(avatar_path, 'wb') as f:
        f.write(friend.get_avatar())
        f.close()


# 拼接用户头像
def createImg():
    x = 0
    y = 0
    imgs = os.listdir(sys.path[0]+'/static/imgs/')
    random.shuffle(imgs)
    # 创建640*640的图片用于填充各小图片
    newImg = Image.new('RGBA', (640, 640))
    # 以640*640来拼接图片，math.sqrt()开平方根计算每张小图片的宽高，
    width = int(math.sqrt(640 * 640 / len(imgs)))
    # 每行图片数
    numLine = int(640 / width)
    for img in imgs:
        if img:
            img_d = Image.open(sys.path[0]+'/static/imgs/'+img)
            # 缩小图片
            img_d = img_d.resize((width, width), Image.ANTIALIAS)
            # 拼接图片，一行排满，换行拼接
            newImg.paste(img_d, (x * width, y * width))
            x += 1
            if x >= numLine:
                x = 0
                y += 1
    newImg.save(sys.path[0]+'/static/' + "all.png")